package com.newlink.building.main.ui

import android.Manifest
import android.content.DialogInterface
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Looper
import android.provider.Settings
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.Gravity
import android.view.View
import android.view.WindowManager
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.google.android.material.snackbar.Snackbar
import com.newlink.building.common_base.base.NL_BaseMvpActivity
import com.newlink.building.common_base.constant.Base_DeviceType
import com.newlink.building.common_base.event.*
import com.newlink.building.common_base.ext.setNewOrAddData
import com.newlink.building.common_base.ext.showToast
import com.newlink.building.common_base.model.bean.DeviceData
import com.newlink.building.common_base.model.bean.DeviceListRequest
import com.newlink.building.common_base.model.bean.DoorData
import com.newlink.building.common_base.model.bean.OpenDoorRequest
import com.newlink.building.common_base.model.bean.OpenDoorResult
import com.newlink.building.common_base.model.bean.ProjectData
import com.newlink.building.common_base.model.bean.RecordMessageReadResult
import com.newlink.building.common_base.utils.DialogUtil
import com.newlink.building.common_base.utils.KeyBoardUtil
import com.newlink.building.common_base.utils.NLog
import com.newlink.building.common_base.utils.PermissionHelper
import com.newlink.building.common_base.utils.WeakHandler
import com.newlink.building.common_base.widget.SpaceItemDecoration
import com.newlink.building.main.R
import com.newlink.building.main.adapter.Module_Main_HomeAdapter
import com.newlink.building.main.databinding.ActivitySearchBinding
import com.newlink.building.main.mvp.contract.Module_Main_HomeContract
import com.newlink.building.main.mvp.presenter.Module_Main_HomePresenter
import com.newlink.building.main.other.Module_Main_MqttUtils
import com.newlink.building.NL_App.Companion.coreContext
import com.newlink.building.manager.Module_Phone_VoipController
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * Created by xiaodong on 2022/9/21.
 */
class Module_Main_SearchActivityNL : NL_BaseMvpActivity<Module_Main_HomeContract.View, Module_Main_HomeContract.Presenter>(),
    Module_Main_HomeContract.View {
    //    override fun attachLayoutRes(): Int = R.layout.activity_search
    private lateinit var mBinding: ActivitySearchBinding
    override fun attachLayoutRes(): View {
        mBinding = ActivitySearchBinding.inflate(layoutInflater)
        return mBinding.root
    }

    companion object {
        private const val MSG_SEARCH = 1000
        private const val MSG_SEARCH_DELAY_TIME = 500L
    }

    //当前页数
    private var pageNum = 1

    //每页加载数量
    private var pageLimit = 20
    private var searchDeviceDatas: MutableList<DeviceData> = mutableListOf()
    private var empty_content: View? = null

    private val weakHandler = WeakHandler(Looper.getMainLooper()) {
        when (it.what) {
            MSG_SEARCH -> {
                searchAction()
            }
        }
        false
    }

    //makeCall 参数
    private var mDevType = -1
    private var mSip = ""
    private var mDevName = ""

    private val mHomeAdapter: Module_Main_HomeAdapter by lazy {
        Module_Main_HomeAdapter()
    }


    override fun initData() {
    }

    override fun initView() {
        super.initView()
        showSoftInputFromWindow(mBinding.etSearch)
        empty_content = findViewById(R.id.empty_content)
        initCallErrorMessage()
//        mBinding.etSearch.isFocusable = true;
//        mBinding.etSearch.isFocusableInTouchMode = true;
//        mBinding.etSearch.requestFocus()
//        (getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager).showSoftInput(mBinding.etSearch,0)

        mBinding.etSearch.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                if (p0?.length == 0) {
                    mBinding.ivClear.visibility = View.GONE
                } else {
                    mBinding.ivClear.visibility = View.VISIBLE
                }
            }

            override fun afterTextChanged(s: Editable?) {
                if (weakHandler.hasMessages(MSG_SEARCH)) {
                    weakHandler.removeMessages(MSG_SEARCH)
                }
                if (TextUtils.isEmpty(s)) {
                    clearDeviceList()
                    empty_content?.visibility = View.GONE
                } else {
//                    weakHandler.sendEmptyMessageDelayed(MSG_SEARCH,MSG_SEARCH_DELAY_TIME)//延迟搜索
                }
            }

        })

        mBinding.etSearch.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                pageNum = 1
                searchAction()
            }
            false
        }

        mBinding.imageSearch.setOnClickListener {
            pageNum = 1
            searchAction()
        }

        mBinding.ivBack.setOnClickListener {
            finish()
        }

        mBinding.ivClear.setOnClickListener {
            mBinding.etSearch.text.clear()
        }

        mBinding.recyclerView.run {
            layoutManager = LinearLayoutManager(context)
            addItemDecoration(SpaceItemDecoration(context))
            adapter = mHomeAdapter
        }

        mHomeAdapter.run {
            animationEnable = false
            setAnimationWithDefault(BaseQuickAdapter.AnimationType.AlphaIn)
            loadMoreModule.setOnLoadMoreListener {
                pageNum++
                searchAction()
            }
            loadMoreModule.isAutoLoadMore = true
            loadMoreModule.isEnableLoadMoreIfNotFullPage = false
            setOnOpenDoorClickListener(object : Module_Main_HomeAdapter.OpenDoorClickListener {
                override fun openDoorClick(view: View, position: Int) {

                    val deviceData = mHomeAdapter.data[position] as DeviceData
//                    mPresenter?.getDoorInfo(accessToken, deviceData.mac)
                    if (deviceData.doors?.size == 1) {
                        val doorNum = searchDeviceDatas[position].doors?.get(0)?.doorNo ?: 1
                        mPresenter?.openDoorAction(
                            OpenDoorRequest(
                                userId, deviceData.mac, doorNum, 1
                            )
//                            OpenDoorRequest(
//                                accessToken, cUserId, KcpRquestType.TYPE_ACTION_OPEN_DOOR,
//                                OpenDoorBody(
//                                    mac = searchDeviceDatas[position].mac,
//                                    doors = arrayListOf(OpenDoorItem(doorNum, 1))
//                                )
//                            )
                        )
                        return
                    }
                    searchDeviceDatas[position].doors?.let {
                        mHomeAdapter.showBottomSheetDialog(
                            position,
                            it
                        )
                    }
                }

                override fun doorLockClick(view: View, position: Int, doorNo: Int) {
                    mPresenter?.openDoorAction(
                        OpenDoorRequest(
                            userId, searchDeviceDatas[position].mac, doorNo, 1
                        )
//                        OpenDoorRequest(
//                            accessToken, cUserId, KcpRquestType.TYPE_ACTION_OPEN_DOOR,
//                            OpenDoorBody(
//                                mac = searchDeviceDatas[position].mac,
//                                doors = arrayListOf(OpenDoorItem(index, 1))
//                            )
//                        )
                    )
                }

                override fun securityClick(view: View, position: Int) {
                    Intent(context, Module_Main_SecurityModelActivityNL::class.java).apply {
                        putExtra("deviceData", searchDeviceDatas[position])
                        startActivity(this)
                    }
                }

                override fun makeCall(type: Int, sip: String, devName: String) {
                    mDevType = type
                    mSip = sip
                    mDevName = devName

                    if (context != null && !PermissionHelper.required(context!!).hasPermission(
                            Manifest.permission.RECORD_AUDIO
                        )
                    ) {
                        requestPermissions(arrayOf(Manifest.permission.RECORD_AUDIO), 0)
                    } else {
                        makeCall()
                    }
                }

                override fun makeMonitorCall(type: Int, sip: String, devName: String) {
                    mDevType = type
                    mSip = sip
                    mDevName = devName
                    Module_Phone_VoipController.get().makeMonitorCall(mSip, mDevName, mDevType)
//                    val sipMsgEvent = MessageEvent(TYPE_CALL_SEND_CREATE_CHANNEL_REQUEST_MONITOR ,CallCreateActionBean(aid = agoraId))
//                    EventBus.getDefault().post(sipMsgEvent)
                }

                override fun onBtIconClicked() {

                }
            })
        }

    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 0) {
            for (i in permissions.indices) {
                when (permissions[i]) {
                    Manifest.permission.RECORD_AUDIO -> if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                        //给了权限
                        makeCall()
                    } else {
                        //拒绝
                        showPermissionDialog()
                    }

                }

            }
        }

    }

    private fun showPermissionDialog() {
        val mDialog = DialogUtil.getConfirmDialog(
            this,
            getString(R.string.permission_content_audio),
            object : DialogInterface.OnClickListener {
                override fun onClick(dialog: DialogInterface?, which: Int) {
                    val intent = Intent()
                    intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
                    val uri = Uri.fromParts("package", packageName, null)
                    intent.data = uri
                    startActivity(intent)
                }
            },
            object : DialogInterface.OnClickListener {
                override fun onClick(dialog: DialogInterface?, which: Int) {

                }
            }).show()
        mDialog.window?.run {
            attributes = attributes.apply {
                width = (windowManager.defaultDisplay.width * 0.95).toInt()
                gravity = Gravity.CENTER
            }
        }
    }


    private fun showSoftInputFromWindow(editText: EditText) {
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE)
        editText.isFocusable = true
        editText.isFocusableInTouchMode = true
        editText.requestFocus()
    }

    override fun createPresenter(): Module_Main_HomeContract.Presenter = Module_Main_HomePresenter()

    override fun refreshDeviceList(total: Int, data: MutableList<DeviceData>) {
        if (pageNum == 1) {//加载第一页,刷新数据
            NLog.e("is first page,set new data")
            resetItemMqttStatus(data)
            mHomeAdapter.setNewOrAddData(true, data)
            searchDeviceDatas.clear()
            searchDeviceDatas = data
        } else {//不是第一页,添加数据
            NLog.e("current page is $pageNum,add data")
            searchDeviceDatas.addAll(data)
            resetItemMqttStatus(data)
            mHomeAdapter.setNewOrAddData(false, data)
        }
        NLog.e("display size:${searchDeviceDatas.size} total:$total pageNum:$pageNum ")

        if (searchDeviceDatas.size < total) {//缓存设备条目小于总数量,需要加载更多
            mHomeAdapter.loadMoreModule.loadMoreComplete()
        } else {
            mHomeAdapter.loadMoreModule.loadMoreEnd()
        }
        if (total < pageLimit) {//设备条目数不够一页,不需要加载更多
            mHomeAdapter.loadMoreModule.loadMoreEnd()
        }
        if (searchDeviceDatas.size > 0) {
            empty_content?.visibility = View.GONE
            mBinding.recyclerView.visibility = View.VISIBLE
        } else {
            empty_content?.visibility = View.VISIBLE
            mBinding.recyclerView.visibility = View.GONE
            findViewById<TextView>(R.id.empty_message).text =
                getString(R.string.search_device_search_empty)
        }
    }

    override fun refreshDoorInfo(data: MutableList<DoorData>) {
//        mHomeAdapter.showBottomSheetDialog(data)
    }

    override fun openDoorResult(result: OpenDoorResult) {

    }

    override fun getMissedCallsSuccess(hasUnreadMsg: Boolean) {
    }

    override fun getUnreadFlagSuccess(haveUnread: Boolean?, msgNum: Int, noticeNum: Int) {
    }

    override fun getPrjListSuccess(data: MutableList<ProjectData>) {
    }

    override fun getRecordUnreadPromptSuccess(result: RecordMessageReadResult) {
    }

    fun clearDeviceList() {
        mHomeAdapter.setNewOrAddData(true, arrayListOf())
    }

    private fun searchAction() {
        val searchKey = mBinding.etSearch.text.toString()
        mBinding.etSearch.clearFocus()
        KeyBoardUtil.hideKeyBoard(this@Module_Main_SearchActivityNL, mBinding.etSearch)
        if (!TextUtils.isEmpty(searchKey)) {
            mPresenter?.getDeviceList(
                DeviceListRequest(
                    accessToken, pageNum, pageLimit, searchKey, null
                )
            )
        }
    }

//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public fun onOpenDoorResult2(event: OpenDoorResultBean) {
//        showOpenDoorResultDialog(event)
//    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onReceiveMsgEvent(event: MessageEvent) {
        when (event.msgType) {
            TYPE_APP_OPEN_DOOR_RESULT -> {
                val result = event.msgContent as OpenDoorResultBean
                showOpenDoorResultDialog(result)
            }
        }

    }


    private fun makeCall() {
        if (Module_Phone_VoipController.get().isCallingState()) {
            showToast(getString(R.string.outgoing_call_not_invite_again))
            return
        }
        when (mDevType) {
            Base_DeviceType.DOORPHONE.code -> Module_Phone_VoipController.get().makeVideoCall(mSip, mDevName)
            else -> Module_Phone_VoipController.get().makeAudioCall(mSip, mDevName)
        }
//        val sipMsgEvent = MessageEvent(TYPE_CALL_SEND_CREATE_CHANNEL_REQUEST_FAMILY ,CallCreateActionBean(aid = agoraId))
//        EventBus.getDefault().post(sipMsgEvent)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMsgReceived(event: MessageEvent) {
        NLog.d("onEventMsgReceived event:$event")
        when (event.msgType) {
            //创建完Channel再进行呼叫
            TYPE_CALL_SEND_CREATE_CHANNEL_RESULT_SEARCH -> {
                when (mDevType) {
                    Base_DeviceType.DOORPHONE.code -> Module_Phone_VoipController.get().makeVideoCall(mSip, mDevName)
                    else -> Module_Phone_VoipController.get().makeAudioCall(mSip, mDevName)
                }
            }

            TYPE_HOME_REFRESH_DEVICE -> {
                searchAction()
            }
//            TYPE_CALL_SEND_CREATE_CHANNEL_RESULT_MONITOR -> {
//                VoipController.get().makeMonitorCall(mSip, mDevName, mDevType)
//            }
        }
    }

    private fun resetItemMqttStatus(deviceDatas: MutableList<DeviceData>) {
        for (item in deviceDatas) {
            item.cMqttConnected = Module_Main_MqttUtils.isConnect() == true
        }
    }

    private fun initCallErrorMessage() {
        coreContext.callErrorMessageResourceId.observe(
            this
        ) {
            it.consume { message ->
                showSnackBar(message)
            }
        }
    }

    override fun showSnackBar(message: String) {
        Snackbar.make(findViewById(android.R.id.content), message, Snackbar.LENGTH_LONG).show()
    }

}